package com.hboxs.asl.wechat.service.impl;

import com.hboxs.asl.Filter;
import com.hboxs.asl.service.impl.BaseServiceImpl;
import com.hboxs.asl.wechat.dao.WechatDao;
import com.hboxs.asl.wechat.dao.WxUserInfoDao;
import com.hboxs.asl.wechat.dao.WxUserLocationDao;
import com.hboxs.asl.wechat.entity.Wechat;
import com.hboxs.asl.wechat.entity.WxUserInfo;
import com.hboxs.asl.wechat.entity.WxUserLocation;
import com.hboxs.asl.wechat.service.WechatService;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by study_000 on 6/27/2015.
 */
@Service(value = "wechatServiceImpl")
public class WechatServiceImpl extends BaseServiceImpl<Wechat, Long> implements WechatService {

    @Resource(name = "wxUserInfoDaoImpl")
    private WxUserInfoDao wxUserInfoDao;
    @Resource(name = "wxUserLocationDaoImpl")
    private WxUserLocationDao wxUserLocationDao;

    @Resource(name = "wechatDaoImpl")
    public void setBaseDao(WechatDao wechatDao) {
        super.setBaseDao(wechatDao);
    }

    @Override
    public Wechat find(String openid) {
        List<Filter> filters = new ArrayList<Filter>();
        filters.add(Filter.eq("openid", openid));

        List<Wechat> wechatList = findList(1, filters, null);
        if (wechatList == null || wechatList.size() == 0) {
            return null;
        }

        return wechatList.get(0);
    }

    @Override
    public Wechat update(Wechat source, WxUserInfo wxUserInfo) {
        Assert.notNull(wxUserInfo);
        if (source.getWxUserInfo() == null) {
            wxUserInfoDao.persist(wxUserInfo);
            source.setWxUserInfo(wxUserInfo);
        } else {
            WxUserInfo userInfo = source.getWxUserInfo();
            copyProperties(wxUserInfo, userInfo, UPDATE_IGNORE_PROPERTIES);
            userInfo.setModifyDate(new Date());
            wxUserInfoDao.merge(userInfo);
            source.setWxUserInfo(userInfo);
        }
        return update(source);
    }

    @Override
    public Wechat update(Wechat source, WxUserLocation wxUserLocation) {
        Assert.notNull(wxUserLocation);
        if (source.getWxUserLocation() == null) {
            wxUserLocationDao.persist(wxUserLocation);
            source.setWxUserLocation(wxUserLocation);
        } else {
            WxUserLocation userLocation = source.getWxUserLocation();
            copyProperties(wxUserLocation, userLocation, UPDATE_IGNORE_PROPERTIES);
            userLocation.setModifyDate(new Date());
            wxUserLocationDao.merge(userLocation);
            source.setWxUserLocation(userLocation);
        }
        return update(source);
    }
}
